package com.bmicpd.gzh.task;

import com.bmicpd.gzh.domain.mapper.GzhInfoSpiderMapper;
import com.google.common.collect.Lists;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 更新任务
 * @author BigZ
 * @date 19-5-28 下午3:28
 */
@Component
@EnableScheduling
@Service
public class UpdateTask {

    private final Logger logger = LoggerFactory.getLogger(UpdateTask.class);

    @Value("${ElasticSearch.HOST}")
    private String esHost;

    @Value("${ElasticSearch.PORT}")
    private int esPort;

    @Value("${ElastisSearch.INDEX}")
    private String esIndex;

    @Value("${ElasticSearch.TYPE}")
    private String esType;

    @Autowired
    private GzhInfoSpiderMapper gzhInfoSpiderMapper;

    @Scheduled(cron = "0/30 * * * * ?")
    private void setGzhUpdateTime(){

        try (TransportClient client = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddresses(
                new InetSocketTransportAddress(InetAddress.getByName(esHost), esPort))){

            // 1. 根据公众号名称聚合
            AggregationBuilder irChannelAgg = AggregationBuilders.
                    terms("irChannelAgg").
                    field("irChannel.raw")
                    .size(2147483647);
            SearchResponse irChannelAggResponse = client.prepareSearch(esIndex).setTypes(esType)
                    .addAggregation(irChannelAgg).execute().actionGet();

            StringTerms stringTerms = (StringTerms)irChannelAggResponse.getAggregations().asMap().get("irChannelAgg");
            Iterator<StringTerms.Bucket> iterator = stringTerms.getBuckets().iterator();

            iterator.forEachRemaining(bucket -> {
                String gzhName = bucket.getKey().toString();
                // 2. 根据公众号名称查询最新文章更新时间
                SearchResponse searchResponse = client.prepareSearch(esIndex)
                        .setTypes(esType).setFrom(0).setSize(1)
                        .setQuery(QueryBuilders.matchPhraseQuery("irChannel", gzhName))
                        .addSort("irUrlTime.keyword", SortOrder.DESC).execute().actionGet();

                SearchHit[] hits = searchResponse.getHits().getHits();
                for(SearchHit hit : hits){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String updateTime = null;
                    try {
                        updateTime = String.valueOf(sdf.parse(hit.getSource().get("irUrlTime").toString()).getTime()/1000);
                    } catch (ParseException e) {
                        logger.error("时间解析异常 ： {}", e);
                    }
                    String gzhNameEn = String.valueOf(hit.getSource().get("irChannel"));
                    logger.info("公众号名称： {}", gzhNameEn);
                    logger.info("时间： {}", String.valueOf(hit.getSource().get("irUrlTime")));
                    logger.info("时间戳： {}", updateTime);
                    gzhInfoSpiderMapper.updateGzhInfoSpider(gzhNameEn, updateTime);
                }
            });
//            while (iterator.hasNext()){
//                StringTerms.Bucket bucket = iterator.next();
//                String gzhName = bucket.getKey().toString();
//                // 2. 根据公众号名称查询最新文章更新时间
//                SearchResponse searchResponse = client.prepareSearch(esIndex)
//                        .setTypes(esType).setFrom(0).setSize(1)
//                        .setQuery(QueryBuilders.matchPhraseQuery("irChannel", gzhName))
//                        .addSort("irUrlTime.keyword", SortOrder.DESC).execute().actionGet();
//
//                SearchHit[] hits = searchResponse.getHits().getHits();
//                for(SearchHit hit : hits){
//                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                    String updateTime = String.valueOf(sdf.parse(hit.getSource().get("irUrlTime").toString()).getTime()/1000);
//                    gzhInfoSpiderMapper.updateGzhInfoSpider(gzhName, updateTime);
//                }
//            }

        } catch (UnknownHostException e) {
            logger.error("Host 未知异常 ： {}", e);
        }

    }
}
